import { Context, Application } from 'egg'

export default (app: Application) => async (ctx: Context, next: () => Promise<any>) => {
  const { authorization } = ctx.header
  if (authorization) {
    const params = authorization.split(' ')
    if (params.length === 2) {
      const [, accessToken] = params
      const payload = await ctx.service.login.verify(accessToken)
      if (payload) ctx.state.user = payload
      else ctx.throw(401, 'accessToken verify error.')
    } else ctx.throw(401, 'Authorization format error.')
  } else ctx.throw(401, 'Authorization not found.')

  await next()
}
